<template>
  <a-form :labelCol="{ span: 4 }">
    <a-form-item label="邮箱" v-bind="validateInfos.email">
      <a-input placeholder="请输入邮箱" v-model:value="formState.email" :disabled="registerLoading" />
    </a-form-item>
    <a-form-item label="验证码" v-bind="validateInfos.code">
      <a-input placeholder="请输入验证码" v-model:value="formState.code"> >
        <template #suffix>
          <a-button type="link" size="small" @click="getEmailCode" :loading="getEmailCodeLoading"
            :disabled="getEmailLock || registerLoading">
            {{ getEmailText }}
          </a-button>
        </template>
      </a-input>
    </a-form-item>

    <a-form-item label="密码" v-bind="validateInfos.password">
      <a-input-password type="password" placeholder="请输入密码" v-model:value="formState.password"
        :disabled="registerLoading" />
    </a-form-item>
    <a-form-item label="确认密码" v-bind="validateInfos.password2">
      <a-input-password type="password" placeholder="请再次输入密码" v-model:value="formState.password2"
        :disabled="registerLoading" />
    </a-form-item>
    <a-form-item>
      <a-button class="w-full" type="primary" @click="registerFun" :loading="registerLoading"
        :disabled="registerLoading">
        注册
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import { message, Form } from 'ant-design-vue';
import { ref, reactive } from 'vue';
import { useUserStore } from '../../../../stores/user'
import { getVerificationCode, register } from '../../../../docsapi/user'

const userStore = useUserStore()
const useForm = Form.useForm;

const getEmailCodeLoading = ref(false);
const getEmailLock = ref(false);
const getEmailText = ref('获取验证码');
const registerLoading = ref(false);

const formState = reactive({
  email: '',
  code: '',
  password: '',
  password2: ''
})

const rules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'change' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'change' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { min: 6, max: 20, message: '密码长度必须在6到20个字符之间', trigger: 'change' }
  ],
  password2: [
    { required: true, message: '请再次输入密码', trigger: 'change' },
    { validator: validatePassword2, trigger: 'change' }
  ]
}
const { validate, validateInfos } = useForm(formState, rules);
function validatePassword2(rule, value, callback) {
  if (value !== formState.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
}

async function getEmailCode() {

  await validate(['email'])

  getEmailCodeLoading.value = true;

  getVerificationCode({ email: formState.email, type: 'register' }).then(data => {
    if (data.code === 0) {
      getEmailLock.value = true;
      getEmailText.value = `60秒后重新获取`;
      message.success('验证码已发送到您的邮箱, 若未收到请检查垃圾邮件或稍后再试');
      let countdown = 60;
      const interval = setInterval(() => {
        countdown--;
        getEmailText.value = `${countdown}秒后重新获取`;
        if (countdown <= 0) {
          clearInterval(interval);
          getEmailText.value = '获取验证码';
          getEmailLock.value = false;
        }
      }, 1000);

    } else {
      // console.error('Error:', data.message);
      message.error(data.error || '获取验证码失败, 请稍后再试');
      getEmailText.value = '获取验证码';
      getEmailLock.value = false;
    }
  }).catch(error => {
    console.error('Error:', error);
    getEmailText.value = '获取验证码';
    getEmailLock.value = false;
    message.error('获取验证码失败, 请稍后再试');
  }).finally(() => {
    getEmailCodeLoading.value = false;
  })
}

async function registerFun() {
  await validate();
  registerLoading.value = true;
  register(formState).then(data => {
    if (data.code === 0) {
      userStore.setToken(data.data.token);
      message.success('登录成功');
    } else {
      // console.error('Error:', data.message);
      message.error(data.error || '注册失败, 请稍后再试');
    }
  }).catch(error => {
    console.error('Error:', error);
    // message.error('注册失败, 请稍后再试');
  }).finally(() => {
    registerLoading.value = false;
  })
}

</script>

<style scoped></style>